package javabase.collection.list.copyonwritearraylist;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

public class CopyOnWriteArrayListDemo1 {
	
	 /**
     * 读线程
     */
    private static class ReadThread implements Runnable {
        List<String> list;
 
        public ReadThread(List<String> list) {
            this.list = list;
        }
 
        public void run() {
            for (String str : list) {
                System.out.println(str);
            }
        }
    }
    /**
     * 写线程
     */
    private static class WriteThread implements Runnable {
        List<String> list;
        int index;
 
        public WriteThread(List<String> list, int index) {
            this.list = list;
            this.index = index;
        }
 
        public void run() {
            list.remove(index);
            list.add(index, "write_" + index);
        }
    }
 
    public void carryOut() {
		final int NUM = 10;
		List<String> list = new ArrayList<String>();
		for (int i = 0; i < NUM; i++) {
		    list.add("main_" + i);
		}
		ExecutorService executorService = Executors.newFixedThreadPool(NUM);
		
		for (int i = 0; i < NUM; i++) {
			executorService.execute(new ReadThread(list));
			executorService.execute(new WriteThread(list, i));
		}
		executorService.shutdown();
    }
 
    public static void main(String[] args) {
    	new CopyOnWriteArrayListDemo1().carryOut();
    }

}

